

const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url')

// Referer防盗链，基于HTTP请求头中Referer字段（例如，Referer黑白名单）来设置访问控制规则，实现对访客的身份识别和过滤，防止网站资源被非法盗用。”

// 本地的服务  a.zf.cn
let server = http.createServer((req, res) => {
    let requestUrl = '.' + req.url; //    ./xxx

    fs.stat(requestUrl, function (err, statObj) {
        if (err) {
            res.statusCode = 404;
            res.end();

        } else if (statObj.isDirectory()) {
            res.end();
        } else {
            console.log(requestUrl);
            // 文件
            if (path.extname(requestUrl) === '.png') {
                let referer = req.headers['referer'] || req.headers['referered'];;  //获取防盗链中的地址
                console.log(referer,req.headers['host']);
                if (referer) {
                    let r1 = req.headers['host']; // 获取客户端的主机名
                    let r2 = url.parse(referer).host
                    if (r1 !== r2) {
                        return fs.createReadStream('./b.png').pipe(res);
                    }
                }
            }
            fs.createReadStream(requestUrl).pipe(res);
        }
    })







});
server.listen(3000);


